import express, {Express, Request, Response, NextFunction} from "express";
import dotenv from "dotenv";
import {createDatabaseInstance} from "./mongoose/connect";
import HttpErrorException from "./exceptions/HttpErrorException";
import errorMiddleware from "./middleware/errorMiddleware";
import {responseMessageMap, responseStatusMap} from "./utils";
import {registerRouter} from "./decorators/registerRouter";
import controller from "./controller";

dotenv.config();
const port = process.env.PORT;
const app: Express = express();
app.use(express.json());
app.use(express.urlencoded());

registerRouter(app, controller);

// 路由找不到
app.use((req: Request, res: Response, next: NextFunction) => {
  const error = new HttpErrorException(responseStatusMap.notFound, responseMessageMap.notFound);
  next(error);
});

app.use(errorMiddleware);


const main = async () => {
  const instance = await createDatabaseInstance();
  if (instance) {
    app.listen(port, () => {
      console.log("数据库连接成功");
      console.log(`serve is running on http://localhost:${port}`);
    });
    // 初始化数据库基本数据
    require("./mongoose/model");
  } else {
    console.log("数据库连接失败");
  }
};
main();




